#include "Obs.h"
#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

Obs::Obs(std::string ip, int port) : Agent(ip, port)
{
}

Obs::~Obs()
{
}

void Obs::start()
{
	char c;
	int size = 0;
	string buf, login;

	cout << "Votre LOGIN : ";
	getline(cin, login);
	size = login.size();
	sendProto("OBS/LOGIN");
	sendInt(size);
	sendString(login.c_str(), size);
	
	buf = getProto();
	if(buf == "OBS/ERR/LOGIN")
	{
		cout << "Erreur : " << buf << endl;
		cout << "Ce login est deja pris." << endl;
		return;
	}
	if(buf != "OBS/LISTE")
		return;
		
	int nbSalles = getInt();
	
	vector<string> rooms;
	
	cout << endl;
	cout << "Liste des salles : " << endl;
	for(int i=0; i<nbSalles; i++)
	{
		size = getInt();
		string roomname = getString(size);
		rooms.push_back(roomname);
		cout << roomname << endl;
	}
	cout << endl;
	
	string roomchoice;

	cout << "Salle choisi (la creer si elle n'existe pas) : ";
	getline(cin, roomchoice);
	
	bool find = false;
	for(vector<string>::iterator it = rooms.begin(); it != rooms.end() && !find; ++it)
	{
		if((*it) == roomchoice)
			find = true;
	}
	
	sendProto("OBS/CHOIX");
	sendInt(roomchoice.size());
	sendString(roomchoice.c_str(), roomchoice.size());
	
	buf = getProto();
	
	if(buf == "OBS/OK/CHOIX")
		cout << "Choix accepte" << endl;
	else
	{
		cout << "Erreur : " << buf << endl;
		cout << "Choix invalide" << endl;
	}
	
	if(!find)
	{
		string nbAct_str;
		cout << "Combien d'activités voulez-vous créer : ";
		getline(cin, nbAct_str);
		std::istringstream iss(nbAct_str);
		int nbAct;
		iss >> nbAct;
		if(nbAct > 4 )
		{
			nbAct = 4;
			cout << "Maximum : 4." << endl;
		}
		sendProto("OBS/ACTIVITES");
		sendInt(nbAct);
		string actName = "";
		for(int i=0; i<nbAct; i++)
		{
			cout << "Choisissez une activité à créer : ";
			getline(cin, actName);
			sendInt(actName.size());
			sendString(actName.c_str(), actName.size());
		}
		
		buf = getProto();
		if(buf == "OBS/ACTIVITES/OK")
		{
			cout << endl;
			cout << "Liste des activites de la salle " << roomchoice << endl;
			int size = getInt();
			int size_str;
			for(int i=0; i< size; i++)
			{
				size_str = getInt();
				cout << "     " << getString(size_str) << endl;
			}
		}
		cout << "En attente de messages ..." << endl;
		while(buf != "uknown")
		{
			buf = getProto();
			cout << "réponses aux qcm " << endl;
			if(buf == "ETUD/OBS/REP/QCM")
			{
				size = getInt();
				buf = getString(size);
				cout << buf << endl;
			}
		}
	}
}
